/**
 * 生成UUID
 * @returns {string}
 */
export function getUuid() {
	let s = [];
	let hexDigits = "0123456789abcdef";
	for (let i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";
	return s.join("");
}


/**
 * 获取文件名
 * @param { String } tempFilePath 文件缓存地址
 */
export function getFileName(tempFilePath) {
	tempFilePath = decodeURIComponent(tempFilePath).split('?')[0];
	const index = tempFilePath.lastIndexOf("\/");
	const fileName = tempFilePath.substring(index + 1, tempFilePath.length);
	// const fileName = tempFilePath.substring(index + 1, tempFilePath.length);
	const fileType = tempFilePath.split('.').pop().toLocaleLowerCase();
	return {
		fileName: fileName,
		fileType: fileType
	};
}

/**
 * 错误弹窗
 * @param {String } errorInfo 错误信息
 */
export function showErrorToast(errorInfo) {
	wx.showToast({
		icon: 'error',
		title: errorInfo,
	})
}

/**
 * 权限校验
 * @param { String } scopeStr 需要鉴权的功能码 
 * @returns
 */
export function checkPermisson(scopeStr) {
	return new Promise((resolve, reject) => {
		wx.getSetting({
			success: async (res) => {
				const authSettingObj = res.authSetting
				if (authSettingObj[scopeStr] === true) {
					// 当前已经有权限了
					console.log('当前已经有权限了', scopeStr)
					return resolve(true)
				} else if (authSettingObj[scopeStr] === false) {
					// 之前问过权限，但是拒绝了
					console.log('之前问过权限，但是拒绝了', scopeStr)
					// 打开setting
					try {
						await wx.openSetting(scopeStr)
						return resolve(true)
					} catch {
						return reject(false)
					}
				} else {
					// 未获取权限
					console.log('未获取权限', scopeStr)
					// 去请求授权
					wx.authorize({
						scope: scopeStr,
						success: (res) => {
							return resolve(true)
						},
						fail: async (err) => {
							// 拒绝授权了
							// 打开setting
							try {
								await wx.openSetting(scopeStr)
								return resolve(true)
							} catch {
								return reject(false)
							}
						},
					})
				}
			},
		})
	})
}
